package sk.talker.atlantis.icefaces.beans;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import com.icesoft.faces.webapp.xmlhttp.*;
import com.icesoft.faces.async.render.*;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlPanelGrid;

public class TalkerOutputBean implements Renderable {
	
	private PersistentFacesState state;
	private OnDemandRenderer chatWriter;
	private TalkerTelnetBean talker;

	private HtmlPanelGrid chatarea;

	public TalkerOutputBean() {
        init();
    }
	
	private void init() {
		state = PersistentFacesState.getInstance();
		chatarea = new HtmlPanelGrid();
		talker = (TalkerTelnetBean)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("talkerTelnetBean");
	}
	
	private void read() {
		String telnetStream = "";
		List chatAreaChildren = null;
		while((telnetStream = talker.read()) != null) {
			HtmlOutputText telnetText = new HtmlOutputText();
			telnetText.setEscape(false);
			telnetText.setValue(telnetStream);
			chatAreaChildren = chatarea.getChildren(); 
			chatAreaChildren.add(telnetText);
			chatWriter.requestRender();
		}
	}

    public HtmlPanelGrid getChatarea() {
		return chatarea;
	}

	public void setChatarea(HtmlPanelGrid chatarea1) {
		this.chatarea = chatarea1;
	}

	public void setRenderManager(RenderManager renderManager) {
		chatWriter = renderManager.getOnDemandRenderer("chatWriter");
		chatWriter.add(this);
		chatWriter.requestRender();
	}
	
	public RenderManager getRenderManager() {
        return null;
    }
	
	public PersistentFacesState getState() {
		return state;
	}

	public void renderingException(RenderingException renderingException) {
		performCleanup();
	}
	
	protected boolean performCleanup(){
        try{
            if(chatWriter != null){
                chatWriter.requestStop();
                chatWriter.remove(this);
                chatWriter.dispose();
                chatWriter = null;
            }
            return true;
        } catch (Exception failedCleanup){
        	//TODO: ...
        	failedCleanup.printStackTrace();
        }
        return false;
    }
}
